<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\model\Sms;
use App\Http\model\Curdpost;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\User;
use Illuminate\Support\Facades\Cache;

class LoginController extends BaseController
{
    /**
     * 登录信息接口
     * by 吉星
     */
    // 登录获取验证码
    public function code(Request $request){
        // $news = new Curdpost();
        // $arr = ['CompanyId'=>'111','Address'=>110100,'DriverNationality'=>'中国2222'];
        // $id = 4;
        // $where = "id=".$id;
        // $res = $news->NewUpdate("driver",$arr,$where);
        // dd($res);
        // exit;
        $arr = [];
        if(empty($request['phone'])){
            $arr['code'] = "1004";
            $arr['message'] = "手机号不能为空";
        }else{
            $phone = $request['phone'];
            // dump($com);
            // dump($company_data);exit;
            $num = rand(1111,9999);
            $msg = "验证码:".$num."，有效期3分钟【时代出行】";
            $code = new Sms();
            $re = $code -> sendSMS($phone,$msg);
            $data = json_decode($re,true);
            //  dump($data);

            if($data['error'] == 0){
                $arr['code'] = "1000";
                // $arr['m_code'] = $num;
                $arr['message'] = '请求成功';
            }else{
                $arr['code'] = "1002";
                if($data['msg'] == 'FREQUENCE_ERROR'){
                    $arr['message'] = '请勿点击太快!';
                }elseif($data['msg'] == 'MOBILE_IN_BLACKLIST'){
                    $arr['message'] = '该号码被列入短信黑名单,请联系本系统工作人员!';
                }else{
                     $arr['message'] = '短信发送失败!';
                     $arr['msg'] = $data['msg'];
                }
            }
            Cache::set('M_CODE',$num,3600);
            Cache::set('PHONE',$phone,3600);
        }
        return $arr;
    }
    // 验证手机验证码
    public function code_yz(Request $request){
        $phone = isset($request['phone']) ? $request['phone'] : false;
        $code = isset($request['code']) ? $request['code'] : false;
        if($phone && $code){
            $cache_code = Cache::get('M_CODE');
            $cache_phone = Cache::get('PHONE');
            if($phone == $cache_phone && $code == $cache_code){
                Cache::forget('M_CODE');
                Cache::forget('PHONE');
                $res['code'] = "1000";
                $res['message'] = "验证成功";
                $res['phone'] = strval($phone);
            }else{
                $res['code'] = "1001";
                $res['message'] = "验证失败";
            }
        }else{
            $res['code'] = "1002";
            $res['message'] = "参数错误";
        }
        return $res;
    }
    // 密码登录
    public function login(Request $request){
        //极光推送吗 放到 Cache里
        // 验证码 手机号判断
        /*
        $arr = [];
        if($request['phone']){
            $data = $request->query();
            $jiguangcode = $data['jiguangcode']; //激光码
            // dump(Cache::get('M_CODE'));
            $m_code = $data['m_code']; //验证码
            $session_code = Cache::get('M_CODE');
            $phone = Cache::get('PHONE');
            if($session_code == $m_code && $phone == $data['phone']){
                Cache::forget('M_CODE');
                Cache::forget('PHONE');
                $data['phone'] = $data['phone'];
                $re = Db :: table('social_user')->where('phone',$data['phone'])->first();
                $re =  json_decode(json_encode($re),true);
                if($re && $re['is_delete'] !=1){
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    session('SOCIAL_USER_ID', $re['id']);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                }elseif($re && $re['is_delete'] ==1){
                    $user['company_id'] = '';
                    $user['limit_rule_id'] = '';
                    $user['is_delete'] = 0;
                    $user['jpush_code'] = $jiguangcode;
                    $user['model_status'] = $data['model_status'];
                    $save = Db::table('social_user')->where('phone',$data['phone'])->update($user);
                    $users = User::where('phone',$data['phone'])->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                    session('SOCIAL_USER_ID', $re['id']);
                }else{
                    $insetArr = [
                        'phone'=>$data['phone'],
                        'jpush_code'=>$jiguangcode,
                        'model_status'=>$data['model_status']
                    ];
                    $id = Db :: table('social_user')->insertGetId($insetArr);
                    $users = User::where('id',$id)->first();
                    $token = JWTAuth::fromUser($users);
                    $arr['token'] = $token;
                    session('SOCIAL_USER_ID', $id);
                }
                $arr['code'] = "1000";
                $arr['message'] = '登录成功';
            }else{
                $arr['code'] = "1002";
                $arr['message'] = '登录失败,验证码不正确';
            }    
            // dump($users);
        }else{
            $arr['code'] = "1001";
            $arr['message'] = '登录失败,手机号不能为空';
        }
        */

        $jiguangcode = isset($request['jiguangcode']) ? $request['jiguangcode'] : false; //激光码
        $model_status = isset($request['model_status']) ? $request['model_status'] : false; //设备类型
        $phone = isset($request['phone']) ? $request['phone'] : false;
        $password = isset($request['password']) ? "###" . md5(md5(trim($request['password']))) : false;
        if($phone && $password){
            $user = Db::table('driver')
                ->where('driver_phone','=',$phone)
                ->where('password','=',$password)
                ->first();
            $user = json_decode(json_encode($user),true);
            if($user){
                $users = User::where('id',$user['id'])->first();
                $token = JWTAuth::fromUser($users);
                // 每次登陆更新token值
                $data['jiguangcode'] = $jiguangcode;
                $data['model_status'] = $model_status;
                if($user['account_status']==4){
                    $data['account_status'] = 1;
                    $ak = 'RGwhFRkSZfva32BN96csoObm4FIfiCAY';
                    $serid = 158008;
                    $url = 'http://yingyan.baidu.com/api/v3/entity/add?ak='.$ak.'&service_id='.$serid.'&entity_name='.$phone;
                    $re = $this->get_curl_json($url);
                }
                $data['save_time'] = date("Y-m-d H:i:s",time());
                $data['token'] = $token;
                Db::table('driver')->where('id',$user['id'])->update($data);
                $userss = Db::table('driver')->where('id',$user['id'])->first();
                $userss = json_decode(json_encode($userss),true);
                // $token = JWTAuth::fromUser($users);
                $tokens = $userss['token'];
                
                $res['token'] = $tokens;
                $res['code'] = "1000";
                $res['message'] = "登录成功";
                $res['phone'] = $user['driver_phone'];
            }else{
                $res['code'] = "1001";
                $res['message'] = "登录失败,用户不存在或者密码错误,请确认后重试";
            }
        }else{
            $res['code'] = "1002";
            $res['message'] = "参数错误";
        }
        return $res;
    }
    /**
     * 模拟get请求
     * @param $url
     * @return mixed
     */
    private function get_curl_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            print_r(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($result,TRUE);
    }
    // 重置密码
    public function repassword(Request $request){
        if($request['phone']){
            $data['password'] = "###" . md5(md5(trim($request['password'])));
            $save = Db::table('driver')->where('driver_phone',$request['phone'])->update($data);
            if($save){
                $res = ['code'=>"1000",'message'=>'修改密码成功!'];
            }else{
                $res = ['code'=>"1001",'message'=>'修改密码失败,没有数据发生变化!'];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!'];
        }
        return $res;
    }
    // 注册协议
    public function xieyi(Request $request){
        if($request){
            return redirect('login/xieyi');
            // return redirect('http://www.baidu.com');
        }
    }
    // 个人中心页面赋值
    public function userinfo(Request $request){
        $user_id = $request->get('id');
        $data = [];
        if($user_id){ // convoy_id
            $user = Db::table('driver as a')
                ->join('convoy as d','a.convoy_id','=','d.id','left')
                ->join('car_car as c','a.car_id','=','c.id','left')
                ->join('car_type as t','c.typeid','=','t.id','left')
                ->join('car_series as s','t.sid','=','s.id','left')
                ->join('branch as b','b.id','=','d.branch_id','left')
                ->where('a.id','=',$user_id)
                ->select('a.id','a.driver_name','a.user_pic','c.num','t.name as typename','s.name as seriesname','d.name','c.color','b.company_name')
                ->first();
            $user = json_decode(json_encode($user),true);
            // print_r($user);exit;
            // foreach ($user as $key => $value) {
                $user['id'] = (string)$user['id'];
            // }
            if($user){
                // 备注: id => 司机id driver_name => 司机名称 user_pic=> 头像 num=> 车牌 typename=>车型名称 seriesname => 车系名称 name=>车队名称 color =>车辆颜色 company_name=>公司名称
                $res = ['code'=>"1000",'message'=>"获取数据成功",'data'=>$user];
            }else{
                $res = ['code'=>"1001",'message'=>"没有找到要查询的数据",'data'=>$data];
            }
        }else{
            $res = ['code'=>"1002",'message'=>"参数错误",'data'=>$data];
        }
        return $res;
    }
    // 编辑资料页面赋值
    public function edit(Request $request){
        $uid = $request->get('id');
        // dump($uid);
        $data = [];
        if($uid){
            $user = Db::table('driver as a')
                ->join('convoy as d','a.convoy_id','=','d.id','left')
                ->join('car_car as c','a.car_id','=','c.id','left')
                ->join('branch as b','b.id','=','d.branch_id','left')
                ->where('a.id',$uid)
                ->select("a.*",'b.company_name','d.name as dname','c.num','b.area')
                ->first();
            $user = json_decode(json_encode($user),true);
            $user['id'] = (string)$user['id'];
            // dd($user);exit;
            if($user['area']){
                $area = Db::table("region")
                    ->where('code',$user['area'])
                    ->first();
                $area =  json_decode(json_encode($area),true);
                $paranarea = Db::table('region')
                    ->where('code',$area['parentCode'])
                    ->first();
                $paranarea =  json_decode(json_encode($paranarea),true);
                $paranareas = Db::table('region')
                    ->where('code',$paranarea['parentCode'])
                    ->first();
                $paranareas =  json_decode(json_encode($paranareas),true);
            }
            $user['areaname'] = $paranareas['fullName'].$paranarea['fullName'].$area['fullName'];
            // company_name=>机构名称  dname=>车队名称 num=>车辆号牌 area=>地区编码 areaname=>地区名称
            if($user){
                $res = ['code'=>"1000",'message'=>"获取数据成功",'data'=>$user];
            }else{
                $res = ['code'=>"1001",'message'=>'没有找到要查询的数据','data'=>$data];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误','data'=>$data];
        }
        return $res;
    }
    // 编辑资料提交
    public function post_edit(Request $request){
        $uid = $request->get('id');
        if($uid){
            $dat = $request->all();
            $data = array_splice($dat,1);
            // dd($data['s']);
            // dd($data);
            $pic = $request['pictype'] ? $request['pictype'] : '';
            if($pic == 'file1'){
                $file = $request->file('user_pic');//获取个人照片
            }
            if($pic == 'file2'){
                $file = $request->file('pin_pic');//获取个人身份证正面照片
            }
            if($pic == 'file3'){
                $file = $request->file('passport_pic');//健康证照片
            }
            if($pic == 'file4'){
                $file = $request->file('licenseId_pic');//驾驶证照片
            }
            if($pic == 'file5'){
                $file = $request->file('pinf_pic');//获取个人身份证反面照片
            }
            $info = Db::table('driver')
                ->where('id',$uid)
                ->first();
            $info = json_decode(json_encode($info),true);
            // return $file;
            // dd($file);
            $data['age'] = !empty($data['age']) ? $data['age'] : $info['age'];
            $data['driver_name'] = !empty($data['driver_name']) ? $data['driver_name'] : $info['driver_name'];
            $data['email'] = !empty($data['email']) ? $data['email'] : $info['email'];
            $data['language'] = !empty($data['language']) ? $data['language'] : $info['language'];
            $data['proficiency'] = !empty($data['proficiency']) ? $data['proficiency'] : $info['proficiency'];
            $data['home_address'] = !empty($data['home_address']) ? $data['home_address'] : $info['home_address'];
            $data['contact'] = !empty($data['contact']) ? $data['contact'] : $info['contact'];
            $data['contact_phone'] = !empty($data['contact_phone']) ? $data['contact_phone'] : $info['contact_phone'];
            $data['condition'] = !empty($data['condition']) ? $data['condition'] : $info['condition'];
            $data['examination_time'] = !empty($data['examination_time']) ? $data['examination_time'] : $info['examination_time'];
            $data['previous_history'] = !empty($data['previous_history']) ? $data['previous_history'] : $info['previous_history'];
            $data['licenseId_type'] = !empty($data['licenseId_type']) ? $data['licenseId_type'] : $info['licenseId_type'];
            $data['licenseId_old'] = !empty($data['licenseId_old']) ? $data['licenseId_old'] : $info['licenseId_old'];
            if (!empty($file)) {
               $file_path = 'uploads/' . date("Ym") . "/";
                $extension = $file->getClientOriginalExtension();//上传文件的后缀.
                $file_name = md5(time() . mt_rand(10, 99)) . '.' . $extension;
                $info = $file->move($file_path, $file_name);
                // return $info;
                if (!$info) {
                    $error = $file->getError();
                    return response(['msg' => $error, 'code' => '1011', 'message' => '图片保存到本地失败']);
                }
                if($pic == 'file1'){
                    $data['user_pic'] = $file_path . $file_name; //获取个人照片
                }
                if($pic == 'file2'){
                    $data['pin_pic'] = $file_path . $file_name;//获取个人身份证正面照片
                }
                if($pic == 'file3'){
                    $data['passport_pic'] = $file_path . $file_name;//健康证照片
                }
                if($pic == 'file4'){
                    $data['licenseId_pic'] = $file_path . $file_name;//驾驶证照片
                }
                if($pic == 'file5'){
                    $data['pinf_pic'] = $file_path . $file_name;//获取个人身份证反面照片
                }
            }
            
            $news = new Curdpost();
            /*
            CertificateNo 网络预约出租汽车驾 驶员资格证号 暂时为空 后期后台手动录入 
            NetworkCarlssueOrganization网络预约出租汽车驾 驶员证发证机构 暂时为空 后期后台手动录入
            NetworkCarlssueDate  资格证发证曰期 暂时为空 后期后台手动录入
            GetNetworkCarProofDate  初次领取资格证日期 暂时为空 后期后台手动录入
            NetworkCarProofOn 资格证有效起始曰期 暂时为空 后期后台手动录入
            NetworkCarProofOff 资格证有效截止曰期 暂时为空 后期后台手动录入
            RegisterDate 驾驶员信息向服务所在 地出租汽车行政主管部 门报备曰期 暂时为空 后期后台手动录入
            CommercialType 1:网络预约出租汽车 2:巡游出租汽车 3:私人小客车合乘 暂时为 1
            ContractCompany 驾驶员合同（或协议） 签署公司 暂时为空 后期后台手动录入
            ContractOn 合同（或协议）有效期 起 
            */
            unset($data['pictype']);
            $data['save_time'] = date("Y-m-d H:i:s",time());
            $save = Db::table('driver')->where('id','=',$uid)->update($data);
            
            $driver_info = Db::table("driver")->where("id",$uid)->first();
            $driver_info = json_decode(json_encode($driver_info),true);
            if($driver_info['sex']==1){
                $xingbie = "男";
            }else{
                $xingbie = "女";
            }
            $arr = ['CompanyId'=>'test','Address'=>110100,'DriverPhone'=>$driver_info['driver_phone'],'DriverName'=>$driver_info['driver_name'],'DriverGender'=>$xingbie,'DriverBirthday'=>substr($driver_info['pin_number'], 6,8),'DriverNation'=>$driver_info['nation'],'DriverContactAddress'=>$driver_info['home_address'],'GetDriverLicenseDate'=>date("Ymd",strtotime($driver_info['frist_time'])),'DriverLicenseOn'=>date("Ymd",strtotime($driver_info['licenseId_firsttime'])),'DriverLicenseOff'=>date("Ymd",strtotime($driver_info['licenseId_endtime'])),'TaxiDriver'=>1,'CertificateNo'=>'暂时为空','NetworkCarlssueOrganization'=>'暂时为空','NetworkCarlssueDate'=>'20180619','GetNetworkCarProofDate'=>'20180619','NetworkCarProofOn'=>'20180619','RegisterDate'=>'20180619','CommercialType'=>1,'ContractCompany'=>'暂时为空','ContractOn'=>'20180619','ContractOff'=>20180619,'State'=>1,'Flag'=>2,'DriverAddress'=>$driver_info['participant'],'EmergencyContact'=>$driver_info['contact'],'EmergencyContactPhone'=>$driver_info['contact_phone'],'Licenseld'=>$driver_info['licenseId'],'UpdateTime'=>date("YmdHis",time())];
            // $id = 4;
            $phone = $request->get('driver_phone');
            // $where = "id=".$id;
            $where = "DriverPhone=".$phone;
            $ress = $news->NewUpdate("driver",$arr,$where);
            
            if($save & $ress){
                $res = ['code'=>"1000",'message'=>'修改成功!'];
            }else{
                $res = ['code'=>"1001",'message'=>'修改失败,没有数据发生变化!'];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!'];
        }
        return $res;
    }
    // 我的钱包  --- 暂时不做
    public function mypurse(Request $request){
        $uid = $request->get('id');
        $data = [];
        if($uid){
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!'];
        }
        return $res;
    }
    // 我的任务
    public function myorder(Request $request){
        $uid = $request->get('id'); //司机ID
        $data = [];
        $where = [];
        // 判读是否有查询条件 
        if($request['order_type']){
            $where['implementstatus'] = $request['order_type'];
        }else{
            $where['implementstatus'] = 3; //如果没有默认状态待接单 2未接单,7进行中,9已完成 1
        }
        if($request['gaipai']){
            $where['reassignment'] = 1;
        }
        if($request['quxiao']){
            $where['orderstatus'] = 5;
        }
        if($uid){
            $data = Db::table('order as a')
                ->join('order_extend as b','a.extendid','=','b.id')
                ->join('server_item as c','c.id','=','a.typeid')
                ->where('b.driver_id','=',$uid)
                ->where($where)
                ->select('a.*','b.*','c.name as itemname')
                ->get()
                ->toArray();
            $data = json_decode(json_encode($data),true);
            foreach ($data as $key => $value) {
               $data[$key]['id'] = (string)$value['id'];
               $data[$key]['usetime'] = (string)$value['usetime'];
            }
            if($data){
                $res = ['code'=>"1000",'message'=>'获取数据成功!','data'=>$data];
            }else{
                $res = ['code'=>"1001",'message'=>'获取数据失败,没有找到要查询的数据!','data'=>$data];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!','data'=>$data];
        }
        return $res;
    }
    //工作通知
    public function msg(Request $request){
        $uid = $request->get('id');
        $data = [];
        if($uid){
            $data = Db::table('message_list as a')
                ->join('message as b','a.info_id','=','b.id')
                ->where('a.driver_id',$uid)
                ->where('b.is_delete',1)
                ->get()
                ->toArray();
            $data = json_decode(json_encode($data),true);
            foreach ($data as $key => $value) {
               $data[$key]['id'] = (string)$value['id'];
            }
            if($data){
                $res = ['code'=>"1000",'message'=>'获取数据成功!','data'=>$data];
            }else{
                $res = ['code'=>"1001",'message'=>'没有找到要查询的数据!','data'=>$data];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!','data'=>$data];
        }
        return $res;
    }
    //设置 -> 修改密码
    public function editpassword(Request $request){
        $uid = $request->get('id');
        $repassword = isset($request['repassword']) ? "###" . md5(md5(trim($request['repassword']))) : false;
        $phone = isset($request['phone']) ? $request['phone'] : false;
        $code = isset($request['code']) ? $request['code'] : false;
        if($phone && $code){
            $cache_code = Cache::get('M_CODE');
            $cache_phone = Cache::get('PHONE');
            if($phone == $cache_phone && $code == $cache_code){
                Cache::forget('M_CODE');
                Cache::forget('PHONE');
                $res['phone'] = strval($phone);
                if($uid && $repassword){
                    $data['password'] = $repassword;
                    $repass = Db::table('driver')
                        ->where('id',$uid)
                        ->update($data);
                    if($repass){
                        $res = ['code'=>"1000",'message'=>'修改密码成功!'];
                    }else{
                        $res = ['code'=>"1001",'message'=>'修改失败,没有数据发生变化!'];
                    }
                }else{
                    $res = ['code'=>"1002",'message'=>'参数错误,没有传入用户信息或者新密码!'];
                }
            }else{
                $res['code'] = "1005";
                $res['message'] = "验证失败,验证码不正确";
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误,没有传入手机号或验证码!'];
        }
                
        return $res;
    }
    //设置 -> 意见反馈
    public function fankui(Request $request){
        if($request->get('id')){
            $data['driver_id'] = $request->get('id');
            $data['contents'] = isset($request['contents']) ? $request['contents'] : false;
            $data['create_time'] = date("Y-m-d H:i:s",time());
            $add = Db::table('yjfk')
                ->insert($data);
            if($add){
                $res = ['code'=>"1000",'message'=>'提交成功!'];
            }else{
                $res = ['code'=>"1001",'message'=>'修改失败,数据写入失败!'];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!'];
        }
        return $res;
    }
    //设置 -> 退出登录
    public function loginout(Request $request){
        $uid = $request->get('id');
        $data['token'] = null;
        if($uid){
            $user = Db::table('driver')
                ->where('id',$uid)
                ->update($data);
            if($user){
                $res = ['code'=>"1000",'message'=>'退出登录成功!'];
            }else{
                $res = ['code'=>"1001",'message'=>'退出登录失败,token不存在!'];
            }
        }else{
            $res = ['code'=>"1002",'message'=>'参数错误!'];
        }
        return $res;
    }

   
}
